package com.test.suanfa;

/**
 * K个一组翻转连表
 */
public class K个一组翻转 {

    public static Node queue = null;

    public static void main(String[] args) {
        for (int i = 5; i >= 1; i--) {
            Node node = new Node(i);
            create(node);
        }
        System.out.println(queue); // 1->2->3->4->5
        fn1(queue, 2);
        System.out.println();
    }

    public static Node fn1(Node head, int k) {
        if (head == null || head.next == null) return head; // 定义结束
        Node firstHead = head;
        Node firstTail = head;
        for (int i = 0; i < k - 1; i++) {
            firstTail = firstTail.next;
            if (firstTail == null) return firstHead;
        }

        Node secondHead = firstTail.next;
        firstTail.next = null;
        fanzhuan(firstHead);
        firstHead.next = fn1(secondHead,k);
        return firstTail;
    }

    public static void fanzhuan(Node node){
        Node prev = null,next;
        while (node != null){
            next = node.next;
            node.next = prev;
            prev = node;
            node = next;
        }
    }

    public static void create(Node node) {
        if (queue == null) {
            node.setNext(null);
            queue = node;
        } else {
            node.setNext(queue);
            queue = node;
        }
    }

    static class Node {
        int val;
        Node next;

        public Node(int val) {
            this.val = val;
        }

        public Node(int val, Node next) {
            this.val = val;
            this.next = next;
        }

        public int getVal() {
            return val;
        }

        public void setVal(int val) {
            this.val = val;
        }

        public Node getNext() {
            return next;
        }

        public void setNext(Node next) {
            this.next = next;
        }
    }

}
